﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Deployment.Application;

using IWshRuntimeLibrary;

namespace BadHabit.Factory.Windows {
    /// <summary>
    /// Interaction logic for Settings.xaml
    /// </summary>
    public partial class Settings : BadHabit.WPFTools.ShapedWindow {

        private System.Data.DataRow myMember = null;
        private Data.TeamDataSet dsTeam = new BadHabit.Factory.Data.TeamDataSet();
        

        public Settings(bool onlyConnection) {
            InitializeComponent();

            if (onlyConnection)
                connectionTabItem.IsSelected = true;


            DataContext = BadHabit.Factory.Properties.Settings.Default;

            Client.LoadBacklogUnits();

            BindTeamMember();
             
        }

        private void BindTeamMember() {
            if (Client.TeamMemberDataSet == null)
                return;

            dsTeam = new BadHabit.Factory.Data.TeamDataSet();
            dsTeam.Merge(Client.TeamMemberDataSet.Member);

            if (Client.User == null)
                return;

            myMember = dsTeam.Member.FindByMemberId(Client.User.Identity.Name);
            if (myMember == null)
                return;

            profileTabItem.DataContext = dsTeam.Member.DefaultView[dsTeam.Member.Rows.IndexOf(myMember)];
            
            
            
        }

        private void SaveMember() {
            System.Data.DataSet dsChanges = new System.Data.DataSet();
            dsChanges.Merge(new System.Data.DataRow[] { myMember });

            if (dsChanges.GetChanges() == null)
                return;

            try {
                Client.Service.SaveTeamMemberProfile(Client.ConvertToProxyTeamDataSet(dsChanges));
            } catch (Exception ex) {
                Windows.Error.ShowError(ex, Properties.Resources.COULD_NOT_UPDATE_TEAM_MEMBERS);
                return;
            }
        }


        protected void Settings_Loaded(object sender, RoutedEventArgs e) {
            if(Client.FactoryMainWindow!=null)
                Client.FactoryMainWindow.IsPopUpOpened = true;
        }

        
        protected override void OnClosed(EventArgs e) {
            base.OnClosed(e);
            if(Client.FactoryMainWindow!=null)
                Client.FactoryMainWindow.IsPopUpOpened = false;
        }

        private void Save_Executed(object sender, ExecutedRoutedEventArgs e) {


            if(myMember!=null && Client.IsConnected)
                SaveMember();
            
            
            // if the service URL has changed
            if (!Client.Service.Url.Equals(Properties.Settings.Default.ProjectWebServiceURL) || needsToReconnect) {

                // tries to apply the new service URL
                try {
                    Client.Service.Url = Properties.Settings.Default.ProjectWebServiceURL;
                } catch (Exception) {
                    Windows.Error.ShowAlert("The Service URL is not well formated.");
                    return;
                }

                // connects to the new service
                Client.Connect(true);

               

                if (!Client.IsConnected)                     
                    return;

                //CreateSendToShortCut();
                
            }
            

            // if is network deployed, then sets the auto start
            if (ApplicationDeployment.IsNetworkDeployed) {


                try {

                    // if should start, creates the registry key
                    if (Properties.Settings.Default.StartWithWindows) {
                        Microsoft.Win32.RegistryKey startUp = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(
                        @"Software\Microsoft\Windows\CurrentVersion\RunOnce");

                        string factoryShortcutPath = 
                            System.Environment.GetFolderPath(System.Environment.SpecialFolder.Programs)
                             + "\\Bad Habit Software\\The Scrum Factory\\Scrum Factory.appref-ms";

                        //startUp.SetValue("FactoryClient", "explorer \"" + ApplicationDeployment.CurrentDeployment.UpdateLocation.AbsoluteUri + "\"");
                        startUp.SetValue("FactoryClient", factoryShortcutPath);
                    } else {
                        // if not deletes it
                        Microsoft.Win32.RegistryKey startUp = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\RunOnce", true);
                        startUp.DeleteValue("FactoryClient", false);
                    }
                } catch (Exception) { }
            }
            

            Properties.Settings.Default.Save();
            Client.FactoryMainWindow.effortBar.Refresh();


            Close();
        }

        private void Undo_Executed(object sender, ExecutedRoutedEventArgs e) {
            Properties.Settings.Default.Reload();
            Close();
        }

        bool needsToReconnect = false;

        private void TextBox_TextChanged(object sender, TextChangedEventArgs e) {
            needsToReconnect = true;
        }


        private void CreateSendToShortCut() {

            //if (!ApplicationDeployment.IsNetworkDeployed)
            //    return;

            WshShell theShell = new WshShell();
            IWshShortcut theLink = (IWshShortcut) theShell.CreateShortcut( Environment.GetFolderPath(Environment.SpecialFolder.SendTo) + "\\factoryProject.lnk");
            //theLink.Arguments = "?SendToProject";
            //theLink.TargetPath = ApplicationDeployment.CurrentDeployment.UpdateLocation.AbsoluteUri;
            theLink.TargetPath = "http://intranetservices.foster.srv.br/FactoryClient35/Factory.application";
            theLink.Description = "Send to a Factory Project";
            theLink.Save();
        }

   

    }
}
